import {
  observable,
  action,
  reaction,
} from "mobx";
import HrmBaseStore from "./baseStore";
import {
  message,
  Button,
	Menu,
	Dropdown
} from 'antd';
import {
  WeaSelect,
  WeaBrowser,
  WeaLocaleProvider,
  WeaTools,
  WeaDatePicker
} from 'ecCom';
import {
  WeaTableNew
} from "comsMobx";
import * as api from "../apis/monthCalendar";
import find from 'lodash/find';
import findIndex from 'lodash/findIndex';
import filter from 'lodash/filter';
import flattenDeep from 'lodash/flattenDeep';
import remove from 'lodash/remove';
import {i18n} from '../public/i18n';
import moment from 'moment';
const {
  TableStore
} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

export class HrmAttendanceMonthCalendarReport extends HrmBaseStore {
  /********************* unobservable list *********************/
  shortWeekdays = this.getLocale().lang.format.veryShortWeekdays;
  conditionData;
  radioGroupVal = {}
  selectedSerial = '';
  detailTableInfo;
  selectRefs = [];
  detailParams = {};
  displayColumns = ['lastname', 'subcompany', 'department', 'jobtitle', 'workcode', 'kqCalendar'];
  /********************* unobservable list *********************/

  /********************* dialog info setting *********************/

  /********************* dialog info setting *********************/

  /********************* observable list *********************/
  @observable rightMenus = [];
  @observable spinning = false;
  @observable spinTip = '';
  @observable pageIndex = 1;
  @observable pageSize = 10;
  @observable total = 0;
  @observable radioGroupConfig = [];
  @observable queryDate;
  @observable table = {
    columns: [],
    datas: []
  }
  @observable showHasNotAccount = false;
  @observable replaceDatas = [];
  @observable holidays = [];
  @observable dialogParams = {
    moduleName: 'hrm',
    visible: false,
    style: {
      width: 1000,
      height: 600
    },
    onCancel: () => {
      this.dialogParams.visible = false;
      this.detailParams = {};
    }
  };
  @observable detailTable = new TableStore();
  @observable tabConfig = {
    tabs: [],
    keyParam: "viewCondition",
    activeTabKey: "1",
    tabChangeHandle: key => this.setActiveTab(key, this.tabConfig.resourceId)
  };
  /********************* observable list *********************/

  /********************* computed list *********************/
  /********************* computed list *********************/

  /********************* action list *********************/
  @action clearData = () => {
    this.radioGroupConfig = [];
    this.queryDate = moment().add('M', -1).format('YYYY-MM');
    this.pageIndex = 1;
    this.pageSize = 10;
    this.total = 0;
    this.radioGroupVal = {};
    this.showHasNotAccount = false;
    this.replaceDatas.length = 0;
    this.clearSerial();
  };

  @action clearSerial = () => {
    this.selectedSerial = '';
  }

  @action getQueryParams = (pageIndex, pageSize) => {
    this.pageIndex = pageIndex || 1;
    const params = {
      pageIndex: this.pageIndex,
      ...this.radioGroupVal,
      isNoAccount: this.showHasNotAccount ? '1' : '0',
      attendanceSerial: this.selectedSerial || '',
      month: this.queryDate
    }
    pageSize && Object.assign(params, {pageSize});
    return params;
  }

  @action init = () => {
    this.clearData()
    this.containerInitFinished.authorized = true;
    this.containerInitFinished.init = true;

    api.init().then(rs => {
      rs.map((data, index) => {
        if (data.status === "1" || data.status == null) {
          switch (index) {
            case 0:
              const {conditions, memo} = data;
              this.conditionData = data;
              this.memo = memo;
              this.generateRadioGroupConfig(conditions);
              break;
            case 1:
              this.rightMenus = data.btnMenu;
              break;
          }
        }
      });
    },
    error => {})
  }

  @action generateRadioGroupConfig = (data) => {
    let config = [];
    config = config.concat(data);
    config[0].com = <div style={{marginTop: 5}}><WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@t25aoa`} value={this.queryDate} format='YYYY-MM' onChange={this.onQueryDateChangeHandle}/></div>
    this.radioGroupConfig = config;
  }

  @action onQueryDateChangeHandle = v => {
    this.queryDate = v;
    this.getKQReport(this.getQueryParams(1));
  }

  @action getTopProps = () => {
    let buttons = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vbih7x`} op='setting' size="small" style={{ height: '28px' }} onClick={this.showAll} title={this.showHasNotAccount ? getLabel('31504','显示无账号人员') : getLabel('500013','不显示无账号人员')}>
        <span>
        {
            this.showHasNotAccount ?
            <i className='icon-coms-ShowNoAccount' style={{ color: '#2DB7F5' }} /> 
            : 
            <i className='icon-coms-NoAccountNoDisplay' style={{ color: '#8A8A8A' }} />
        }
        </span>
      </Button>,
    ];
    let menus = [];
    menus.push({
      key: '0',
      content: buttons[0].props.title,
      icon: <i className={this.menuIconCollection[buttons[0].props.op]}/>,
      onClick: () => this.showAll()
    });
    this.toJS(this.rightMenus).map((menu, index) => {
      index > 0 && menus.push({
        key: index.toString(),
        content: menu.menuName,
        icon: <i className={menu.menuIcon}/>,
        onClick: () => {
          switch(menu.type){
            case "BTN_Export_Excel":
              this.exportExcel();
              break;
            case "BTN_KQ_REPORT_FORMAT":
              this.formatData(menu.menuName);
              break;
          }
        }
      });
    });
    menus.push({
      key: menus.length.toString(),
      content: getLabel(354, '刷新'),
      icon: <i className={this.menuIconCollection['sync']}/>,
      onClick: () => this.getKQReport(this.getQueryParams())
    });
    return {
      buttons,
      menus: [
        ...menus,
        ...this.getBasicMenus("HRM_ENGINE_HRM_ANNUAL_MANAGER_SET")
      ]
    };
  };

  redirectToChecking = resourceId => {
    window.location.href = `/wui/index.html#/main/attendance/checking/${resourceId}?fromcard=true`;
  }

  getStyle = d => {
    if(d == null) return {};
    const {status, flowStatus} = d;
    let style = {};
    if(flowStatus != null && flowStatus != ''){
      style.background = (flowStatus == '0' ? this.memo[1].color : this.memo[2].color);
      style.color = '#2195FB';
    }else if(status != null && status != ''){
      switch(d.status){
        case '-1':
          break;
        case '0':
          style = {color: '#48C651'};
          break;
        case '5':
          style = {color: '#2195FB'};
          break;
        default:
          style = {color: '#2195FB', background: this.memo[0].color};
          break;
      }
    }
    return style;
    // switch(d.status){
    //   case '':
    //     return {}
    //   case '-1':
    //     return {};
    //   case '0':
    //     return {color: '#48C651'};
    //   default:
    //     return {color: '#2195FB'};
    // }
  }

  @action convertColumns = (columns) => {
    columns.map((c, i) => {
      delete c.width;
      c.render = (text, record, index) => {
        if (c.dataIndex == 'lastname') {
          return <a onClick={() => this.redirectToChecking(record.resourceId)} title={text}><div className='text-elli'>{text}</div></a>;
        } else{
          let d = record[c.dataIndex];
          if(d){
            return (
              <div>
                {
                  d.length > 0 &&
                  <div style={{height: 30, borderBottom: '1px solid #eee', ...this.getStyle(d[0])}} title={d[0].statusName || ''}>{(d[0].statusName || '').substring(0, 2)}</div>
                }
                {
                  d.length > 1 ?
                  <div style={{height: 30, ...this.getStyle(d[1])}} title={d[1].statusName || ''}>{(d[1].statusName || '').substring(0, 2)}</div>
                  :
                  <div style={{height: 30}}>{''}</div>
                }
              </div>
            )
          }else{
            d = ['', ''];
            return <div>
              <div style={{borderBottom: '1px solid #eee', height: 30}}>{d[0] || ''}</div>
              <div style={{height: 30}}>{d[1] || ''}</div>
            </div>
          }
        }
      }
    });

    return columns;
  }

  @action getKQReport = params => {
    if (this.spinning)
      return;
    this.spinning = true;
    api.getKQReport({
      data: JSON.stringify(params)
    }).then(data => {
      if (data.status === '1' || data.status == null) {
        this.holidays = data.holidays;
        this.table.columns = this.convertColumns(data.columns);
        this.table.datas = data.datas;
        this.pageIndex = data.pageindex;
        this.pageSize = data.pagesize || 10;
        this.total = data.count;
      } else {
        message.error(data.message);
      }
      this.spinning = false;
    }, error => this.spinning = false);
  }

  @action onRadioGroupChange = params => {
    this.radioGroupVal = params;
    switch (params.viewScope) {
      case '1':
        if (params.subCompanyId == null || params.subCompanyId == '') {
          return;
        }
        break;
      case '2':
        if (params.departmentId == null || params.departmentId == '') {
          return;
        }
        break;
      case '3':
        if (params.resourceId == null || params.resourceId == '') {
          return;
        }
        break;
    }
    this.getKQReport(this.getQueryParams(1));
  }

  @action showAll = () => {
    this.showHasNotAccount = !this.showHasNotAccount;
    this.getKQReport(this.getQueryParams());
  }

  @action exportExcel = () => {
    if(this.spinning)
      return;
    this.spinning = true;
    this.spinTip = getLabel('500702','导出数据中，请稍候');
    const params = { 
      ...this.getQueryParams(),
      showColumns: this.displayColumns
    };

    api.exportExcel({data:JSON.stringify(params)}).then(data => {
      this.spinning = false;
      this.spinTip = '';
      if(data.status === '1' && data.url != null && data.url.trim().length > 0)
        WeaTools.downloadFile(data.url, "GET");
    }, error => {
      this.spinning = false;
      this.spinTip = '';
    })
  }

  @action setActiveTab = (key, resourceId) => {
    // const tabIndex = this.getTabIndex(this.toJS(this.tabConfig.tabs), key);
    // if (tabIndex < 0) return;
    this.tabConfig.activeTabKey = key || this.tabConfig.tabs[0].viewCondition;
    this.detailParams.tabKey = this.tabConfig.activeTabKey;
    this.callDetail(resourceId);
  };

  @action showDetail = (resourceId, dataIndex, columnType, source, isCalendar) => {
    this.detailTableInfo = {};
    let params = {
      ...this.radioGroupVal,
      isNoAccount: this.showHasNotAccount ? '1' : '0',
      attendanceSerial: this.selectedSerial || ''
    };
    if(resourceId != null)
      params.resourceId = resourceId;
    if (isCalendar) {
      params = {
        type: source.type,
        date: dataIndex
      };
    } else {
      params = { ...params,
        type: dataIndex
      };
    }
    this.detailParams = params;
    api.getTabs({
      type: params.type
    }).then(data => {
      if (data.status === '1') {
        const {
          tabs: tabArr
        } = data;
        let tabs = [],
          activeIndex = '1';
        if (tabArr != null && tabArr.length > 0) {
          tabArr.map((tab, index) => {
            let tabInfo = {
              color: "#000000",
              groupId: `g${index}`,
              title: tab.title,
              viewCondition: tab.key
            };
            tabs.push(tabInfo);
            if (tab.selected)
              activeIndex = tab.key;
          });
        }
        this.tabConfig.tabs = tabs;
        this.tabConfig.resourceId = resourceId;
        this.setActiveTab(activeIndex, resourceId);
      } else {

      }
    }, error => {})
  }

  disposer = reaction(() => this.dialogParams.visible, visible => {
    if (!visible) this.iskqCalendarDialog = false;
  })

  @observable iskqCalendarDialog = false;

  @observable detail = {
    userInfo: {},
    signInfo: '',
    columns: [],
    datas: [],
  }

  @action showSignDetail = (params) => {
    this.iskqCalendarDialog = true;

    api.getKQReportSignDetial(params).then(data => {
      if (data.status === '1') {
        const {
          userInfo,
          signInfo,
          table,
          dialogTitle
        } = data;

        Object.assign(this.detail.userInfo, userInfo);

        this.detail.signInfo = signInfo.signInfo;

        ['columns', 'datas'].map(v => {
          this.detail[v] = table[v];
        });

        this.dialogParams.title = dialogTitle;
        this.dialogParams.visible = true;
      } else {
        message.error(data.message);
      }
    }, error => {})
  }

  @action callDetail = (resourceId) => {
    let params = {...this.detailParams};
    if(resourceId != null)
      params.resourceId = resourceId;
    api.getKQReportDetial(params).then(data => {
      if (data.status === '1') {
        const {
          dialogTitle,
          sessionkey
        } = data;
        this.dialogParams.title = dialogTitle;
        this.detailTable = new TableStore();
        this.detailTable.getDatas(sessionkey);
        this.dialogParams.visible = true;
      } else {
        message.error(data.message);
      }
    }, error => {})
  }

  @action formatData = content => {
    this.confirmInfo({
      content,
      onOk: () => {
        api.formatData({
          data: JSON.stringify(this.getQueryParams())
        }).then(data => {
          message.success(i18n.message.opSuccess());
          this.getKQReport(this.getQueryParams());
        }, error => {})
      }
    });
  }
  /********************* action list *********************/
}

export const hrmAttendanceMonthCalendarReport = new HrmAttendanceMonthCalendarReport();